package com.honestpeak.datafusion.service.impl;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.honestpeak.core.utils.WeekUtils;
import com.honestpeak.datafusion.common.ServerResponse;
import com.honestpeak.datafusion.enums.ClubMemberEnum;
import com.honestpeak.datafusion.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.honestpeak.core.datasource.DataSourceContextHolder;
import com.honestpeak.core.datasource.DataSourceType;
import com.honestpeak.core.enums.MonthEnum;
import com.honestpeak.core.enums.ScoreEnum;
import com.honestpeak.core.utils.WebUtils;
import com.honestpeak.datafusion.mapper.ClubMemberDistMapper;
import com.honestpeak.datafusion.service.ClubMemberDistService;
import org.springframework.util.CollectionUtils;

@Service
public class ClubMemberDistServiceImpl implements ClubMemberDistService{

	@Resource
	private ClubMemberDistMapper clubMemberDistMapper;

	@Override
	public Map<String, Object> getClubMemberNumByYear(String year) {
		
		if(StringUtils.isEmpty(year)||year==null){
            year = WebUtils.getCourseYear(new Date());
        }
		List<ClubMemberDist> clubMemberDistsList = clubMemberDistMapper.getClubMemberNumByYear(year);
		Map<String, List<ClubMemberDist>> groupMap = new HashMap<String, List<ClubMemberDist>>();

		// 先根据用户类别对list分组，得到 按分组归类的groupMap
		for (int i = 0; i < clubMemberDistsList.size(); i++) {
            //获取每条数据
			ClubMemberDist data = clubMemberDistsList.get(i);
			
			//从分类的map中获取这条数据对应的用户类别对应的 list
			List<ClubMemberDist> templist = groupMap.get(data.getMemberType());
			if (templist == null) {
				templist = new ArrayList<ClubMemberDist>();
				templist.add(data);
				groupMap.put(data.getMemberType(), templist);
			} else {
				templist.add(data);
			}
		}

		List<Map<String, Object>> itemsList = new ArrayList<Map<String, Object>>();

		for (String memberType : groupMap.keySet()) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			List<ClubMemberDist> list = groupMap.get(memberType);
			
			//取该用户类型下的数据
			List<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
			for (ClubMemberDist clubMemberDist : list) {
				
				HashMap<String, Object> tempMap = new HashMap<String, Object>();

				tempMap.put("clubName", clubMemberDist.getClubName());
				tempMap.put("value", clubMemberDist.getPeopleNum());
				items.add(tempMap);
			}
			dataMap.put("items", items);
			dataMap.put("name", memberType);
			itemsList.add(dataMap);
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", itemsList);
		return resultMap;
	}
	
	

	@Override
	public Map<String, Object> getMonthNumActiveCountByYear(String year,String clubName) {
		if(StringUtils.isEmpty(year)){
			year = String.valueOf(WebUtils.getYear(new Date()));
        }
		List<Integer> monthList = WebUtils.AssemblyMonth();
		List<ClubMemberDist> clubMemberDistsList = clubMemberDistMapper.getMonthActiveByYear(monthList,year,clubName);
		Map<String, List<ClubMemberDist>> groupMap = new HashMap<String, List<ClubMemberDist>>();

		// 先根据用户类别对list分组，得到 按分组归类的groupMap
		for (int i = 0; i < clubMemberDistsList.size(); i++) {
            //获取每条数据
			ClubMemberDist data = clubMemberDistsList.get(i);
			
			//从分类的map中获取这条数据对应的用户类别对应的 list
			List<ClubMemberDist> templist = groupMap.get(data.getMemberType());
			if (templist == null) {
				templist = new ArrayList<ClubMemberDist>();
				templist.add(data);
				groupMap.put(data.getMemberType(), templist);
			} else {
				templist.add(data);
			}
		}

		List<Map<String, Object>> itemsList = new ArrayList<Map<String, Object>>();

		for (String memberType : groupMap.keySet()) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			List<ClubMemberDist> list = groupMap.get(memberType);  
			
			//取该用户类型下的数据
			List<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
			for (ClubMemberDist clubMemberDist : list) {
				HashMap<String, Object> tempMap = new HashMap<String, Object>();
				tempMap.put("monthTime", clubMemberDist.getMonthTime());
				tempMap.put("value", clubMemberDist.getPeopleNum());					
				items.add(tempMap);
			}
			dataMap.put("items", items);
			dataMap.put("name", memberType);
			itemsList.add(dataMap);
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", itemsList);
		return resultMap;
	}

	@Override
	public List<String> getYearTermInfo() {
		List<YearTerm> yearTermList = clubMemberDistMapper.getYearTermInfo();
		return yearTermList.stream().map(YearTerm::getYear).distinct().collect(Collectors.toList());
	}



	@Override
	public Map<String, Object> getClubYearNumByYear(String year,String clubName) {
		if(StringUtils.isEmpty(year)){
            year = WebUtils.getCurrentYear(new Date());
        }
		List<ClubMemberDist> clubMemberDistsList = clubMemberDistMapper.getClubYearNumByYear(year,clubName);
		Map<String, List<ClubMemberDist>> groupMap = new HashMap<String, List<ClubMemberDist>>();

		// 先根据用户类别对list分组，得到 按分组归类的groupMap
		for (int i = 0; i < clubMemberDistsList.size(); i++) {
            //获取每条数据
			ClubMemberDist data = clubMemberDistsList.get(i);
			
			//从分类的map中获取这条数据对应的用户类别对应的 list
			List<ClubMemberDist> templist = groupMap.get(data.getTerm());
			if (templist == null) {
				templist = new ArrayList<ClubMemberDist>();
				templist.add(data);
				groupMap.put(data.getTerm(), templist);
			} else {
				templist.add(data);
			}
		}

		List<Map<String, Object>> itemsList = new ArrayList<Map<String, Object>>();

		for (String term : groupMap.keySet()) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			List<ClubMemberDist> list = groupMap.get(term);
			
			//取该用户类型下的数据
			List<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
			for (ClubMemberDist clubMemberDist : list) {
				
				HashMap<String, Object> tempMap = new HashMap<String, Object>();
				tempMap.put("memberType", clubMemberDist.getMemberType());
				tempMap.put("peopleNum", clubMemberDist.getPeopleNum());
				items.add(tempMap);
			}
			dataMap.put("items", items);
			dataMap.put("term", term);
			itemsList.add(dataMap);
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("data", itemsList);
		return resultMap;
	}
	

	/**
	 * 学生班级数据中 班级各俱乐部人数分布
	 * @param departId 院系Id
	 * @param claId 班级Id
	 * @param yearTermId 学年学期Id
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getClubSizeDistribution(Long departId, Long claId, Long yearTermId) {
		//切换数据库
		DataSourceContextHolder.setDbType(DataSourceType.SPORTS);
		List<Map<String, Object>> result = Lists.newArrayList();
		List<BaseModel> baseModelList = clubMemberDistMapper.getClubSizeDistribution(departId, claId, yearTermId);
		baseModelList.stream().forEach(x -> {
			Map<String, Object> map = Maps.newHashMap();
			map.put("name", x.getName());
			map.put("value", x.getValue());
			result.add(map);
		});
		DataSourceContextHolder.clearDbType();
		return result;
	}

	/*
	 * 
	 * 查询所有俱乐部
	 */
	@Override
	public List<String> getClubInfo() {
		
		return clubMemberDistMapper.getClubInfo();
	}

	@Override
	public List<Map<String, Object>> getClassNumScore(Long departId, Long claId, Long yearTermId) {
		List<String> scoreList = WebUtils.FractionScore();
		//切换数据库
		DataSourceContextHolder.setDbType(DataSourceType.SPORTS);
		List<Map<String, Object>> itemsList = Lists.newArrayList();
		scoreList.stream().forEach(x -> {
		ScoreModel scoreModel = clubMemberDistMapper.getClassNumScore(departId, claId, yearTermId,x);
			Map<String, Object> map = Maps.newHashMap();
			map.put("score", getScoreStr(x));
			map.put("value", scoreModel.getValue());
			itemsList.add(map);
		});
		DataSourceContextHolder.clearDbType();
		return itemsList;
	}
	
	/**
     * @param score
     * @return
     */
    private String getScoreStr(String score){
        String scoreStr = "";
        if(score == ScoreEnum.SCORE_FIFTY_NINE.getScorePara()){
        	scoreStr = ScoreEnum.SCORE_FIFTY_NINE.getValue();
        } else if(score == ScoreEnum.SCORE_SIXTY_NINE.getScorePara()){
            scoreStr = ScoreEnum.SCORE_SIXTY_NINE.getValue();
        }else if(score == ScoreEnum.SCORE_SEVENTY_NINE.getScorePara()){
            scoreStr = ScoreEnum.SCORE_SEVENTY_NINE.getValue();
        }else if(score == ScoreEnum.SCORE_EIGHTY_NINE.getScorePara()){
            scoreStr = ScoreEnum.SCORE_EIGHTY_NINE.getValue();
        }else if(score == ScoreEnum.SCORE_NINETY_HUNDRED.getScorePara()){
        	scoreStr = ScoreEnum.SCORE_NINETY_HUNDRED.getValue();
        }
        return scoreStr;
    }

	/**
	 * 每周俱乐部活动人数
	 * @param clubName
	 * @param year
	 * @return
	 */
	@Override
	public ServerResponse getWeekOfYearClubPeopleNum(String clubName, String year){
		List<Map<String, Object>> result = Lists.newArrayList();

		if (StringUtils.isEmpty(year)) {
			year = WebUtils.DateToYearStr(new Date());
		}
		try {
			int weekNum = WebUtils.getWeekOfYear(Integer.valueOf(year));

			DataSourceContextHolder.setDbType(DataSourceType.SPORTS);
			List<ClubSignInfo> clubSignInfoList = clubMemberDistMapper.getClubSignInfo();
			DataSourceContextHolder.clearDbType();

			Map<String, Object> juniorMap = Maps.newHashMap();
			Map<String, Object> intermediateMap = Maps.newHashMap();
			Map<String, Object> seniorMap = Maps.newHashMap();

			List<Map<String, Object>> juniorItemsList = Lists.newArrayList();
			List<Map<String, Object>> intermediateItemsList = Lists.newArrayList();
			List<Map<String, Object>> seniorItemsList = Lists.newArrayList();

			//初级会员
			List<ClubSignInfo> juniorClubSignInfoList = clubSignInfoList.stream().filter(x -> x.getType() == ClubMemberEnum.CLUB_MEMBER_JUNIOR.getCode() && StringUtils.equals(x.getClubName(), clubName)).collect(Collectors.toList());
			//中级会员
			List<ClubSignInfo> intermediateClubSignInfoList = clubSignInfoList.stream().filter(x -> x.getType() == ClubMemberEnum.CLUB_MEMBER_INTERMEDIATE.getCode() && StringUtils.equals(x.getClubName(), clubName)).collect(Collectors.toList());
			//高级会员
			List<ClubSignInfo> seniorClubSignInfoList = clubSignInfoList.stream().filter(x -> x.getType() == ClubMemberEnum.CLUB_MEMBER_SENIOR.getCode() && StringUtils.equals(x.getClubName(), clubName)).collect(Collectors.toList());

			for (int i = 1; i <= weekNum; i++) {
				//一年中 周的开始时间结束时间
				String startWeekTime = WeekUtils.getStartDayOfWeekNo(Integer.valueOf(year), i);
				String endWeekTime = WeekUtils.getEndDayOfWeekNo(Integer.valueOf(year), i);

				//初级会员
				Map<String, Object> juniorItemsMap = Maps.newHashMap();

				long juniorValue = juniorClubSignInfoList.stream().filter(x -> WebUtils.StringToLong(startWeekTime) <=  WebUtils.StringToLong(x.getSignTime()) && WebUtils.StringToLong(endWeekTime) > WebUtils.StringToLong(x.getSignTime())).count();
				juniorItemsMap.put("name", WeekUtils.getWeeks(i));
				juniorItemsMap.put("value", juniorValue);

				//中级会员
				Map<String, Object> intermediateItemsMap = Maps.newHashMap();
				long intermediateValue = intermediateClubSignInfoList.stream().filter(x -> WebUtils.StringToLong(startWeekTime) <=  WebUtils.StringToLong(x.getSignTime()) && WebUtils.StringToLong(endWeekTime) > WebUtils.StringToLong(x.getSignTime())).count();
				intermediateItemsMap.put("name", WeekUtils.getWeeks(i));
				intermediateItemsMap.put("value", intermediateValue);

				//高级会员
				Map<String, Object> seniorItemsMap = Maps.newHashMap();
				long seniorValue = seniorClubSignInfoList.stream().filter(x -> WebUtils.StringToLong(startWeekTime) <=  WebUtils.StringToLong(x.getSignTime()) && WebUtils.StringToLong(endWeekTime) > WebUtils.StringToLong(x.getSignTime())).count();
				seniorItemsMap.put("name", WeekUtils.getWeeks(i));
				seniorItemsMap.put("value", seniorValue);

				juniorItemsList.add(juniorItemsMap);
				intermediateItemsList.add(intermediateItemsMap);
				seniorItemsList.add(seniorItemsMap);

			}
			juniorMap.put("name", "初级会员");
			juniorMap.put("items", juniorItemsList);
			intermediateMap.put("name", "中级会员");
			intermediateMap.put("items", intermediateItemsList);
			seniorMap.put("name", "高级会员");
			seniorMap.put("items", seniorItemsList);

			result.add(juniorMap);
			result.add(intermediateMap);
			result.add(seniorMap);
		}catch (Exception e){
			ServerResponse.createByErrorMessage("系统异常");
		}
		return ServerResponse.createBySuccess(result);
	}

	
	@Override
	public List<Map<String, Object>> getSignSecondNum(Long yearTermId, String studentNo) {
		List<Integer> monthList = WebUtils.AssemblyMonth();
		//切换数据库
		DataSourceContextHolder.setDbType(DataSourceType.SPORTS);
		List<Map<String, Object>> itemsList = Lists.newArrayList();
		monthList.stream().forEach(x -> {
		SignModel signModel = clubMemberDistMapper.getSignSecondNum(yearTermId,studentNo,x);
			Map<String, Object> map = Maps.newHashMap();
			map.put("month", getMonthStr(x));
			map.put("value", signModel.getValue());
			itemsList.add(map);
		});
		DataSourceContextHolder.clearDbType();
		return itemsList;
	}
	
	/**
     * @param month
     * @return
     */
    private String getMonthStr(Integer month){
        String monthStr = "";
        if(month == MonthEnum.MONTH_ENUM_JANUARY.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_JANUARY.getValue();
        } else if(month == MonthEnum.MONTH_ENUM_FEBRUARY.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_FEBRUARY.getValue();
        }else if(month == MonthEnum.MONTH_ENUM_MARCH.getCode()){
            monthStr =MonthEnum.MONTH_ENUM_MARCH.getValue();
        }else if(month == MonthEnum.MONTH_ENUM_APRIL.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_APRIL.getValue();
        }else if(month == MonthEnum.MONTH_ENUM_MAY.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_MAY.getValue();
        }else if(month == MonthEnum.MONTH_ENUM_JUNE.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_JUNE.getValue();
        }else if(month == MonthEnum.MONTH_ENUM_JULY.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_JULY.getValue();
        }else if(month == MonthEnum.MONTH_ENUM_AUGUST.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_AUGUST.getValue();
        }else if(month == MonthEnum.MONTH_ENUM_SEPTEMBER.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_SEPTEMBER.getValue();
        }else if(month == MonthEnum.MONTH_ENUM_OCTOBER.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_OCTOBER.getValue();
        } else if(month == MonthEnum.MONTH_ENUM_NOVEMBER.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_NOVEMBER.getValue();
        } else if(month == MonthEnum.MONTH_ENUM_DECEMBER.getCode()){
            monthStr = MonthEnum.MONTH_ENUM_DECEMBER.getValue();
        }
        return monthStr;
    }

}
